/*
 * See www.dma-games.com for the game logic and design!
 * All classes except PlayerLogic.java and ki.pro are from there
 * (Some are changed).
 * 
 * Ensure that gnuprologjava-0.2.6 is added to the build path
 * before the first run!
 */


import java.awt.BorderLayout;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.management.ManagementFactory;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;


public class Main {

	private static MineSweeperWindow myWindow;
	private static Game myGame;
	private static PlayerLogic prologPlayer;
	
	public static void main(String[] args) {
	    
		//open a new window
		JFrame frame = new JFrame("Java Minesweeper Console");
		frame.setSize(500,250);
		
	    JTextArea consoleText = new JTextArea();
	    JScrollPane scrollPane = new JScrollPane(consoleText);
	    JPanel panel = new JPanel(new BorderLayout());
		
	    panel.add(scrollPane);
        frame.getContentPane().add(panel);
		
		//redirect output stream to newly created window
		TextAreaOutputStream textOut = new TextAreaOutputStream(consoleText);
		PrintStream outStream = new PrintStream(textOut, true);
		System.setOut(outStream);
		frame.setVisible(true);
			
		myWindow = new MineSweeperWindow();
		myGame = myWindow.getGame();
		//myWindow.setGameDifficulty(Game.GAME_DIFFICULTY_INTERMEDIATE);

		try{
			Thread.currentThread().sleep(4000);
		}catch (Exception e) {
			System.out.println("wait failed in method clickOnCell: " + e.getMessage());
		}
		
		prologPlayer = new PlayerLogic(myGame);
		
		try{
			//Thread.currentThread().sleep(2000);
		}catch (Exception e) {
			System.out.println("wait failed in method clickOnCell: " + e.getMessage());
		}
		
		//prologPlayer.clickOnCell(new Point(0,4), MouseEvent.BUTTON2);
		prologPlayer.runPrologPlayer();
		
	}
	

	/** 
	 * Sun property pointing the main class and its arguments. 
	 * Might not be defined on non Hotspot VM implementations.
	 */
	public static final String SUN_JAVA_COMMAND = "sun.java.command";
	
	/**
	 * Restart the current Java application
	 * @param runBeforeRestart some custom code to be run before restarting
	 * @throws IOException
	 */
	public static void restartApplication(Runnable runBeforeRestart) throws IOException {
		try {
			// java binary
			String java = System.getProperty("java.home") + "/bin/java";
			// vm arguments
			List<String> vmArguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
			StringBuffer vmArgsOneLine = new StringBuffer();
			for (String arg : vmArguments) {
				// if it's the agent argument : we ignore it otherwise the
				// address of the old application and the new one will be in conflict
				if (!arg.contains("-agentlib")) {
					vmArgsOneLine.append(arg);
					vmArgsOneLine.append(" ");
				}
			}
			// init the command to execute, add the vm args
			final StringBuffer cmd = new StringBuffer("\"" + java + "\" " + vmArgsOneLine);

			// program main and program arguments
			String[] mainCommand = System.getProperty(SUN_JAVA_COMMAND).split(" ");
			// program main is a jar
			if (mainCommand[0].endsWith(".jar")) {
				// if it's a jar, add -jar mainJar
				cmd.append("-jar " + new File(mainCommand[0]).getPath());
			} else {
				// else it's a .class, add the classpath and mainClass
				cmd.append("-cp \"" + System.getProperty("java.class.path") + "\" " + mainCommand[0]);
			}
			// finally add program arguments
			for (int i = 1; i < mainCommand.length; i++) {
				cmd.append(" ");
				cmd.append(mainCommand[i]);
			}
			// execute the command in a shutdown hook, to be sure that all the
			// resources have been disposed before restarting the application
			Runtime.getRuntime().addShutdownHook(new Thread() {
				@Override
				public void run() {
					try {
						Runtime.getRuntime().exec(cmd.toString());
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			});
			// execute some custom code before restarting
			if (runBeforeRestart!= null) {
				runBeforeRestart.run();
			}
			// exit
			System.exit(0);
		} catch (Exception e) {
			// something went wrong
			throw new IOException("Error while trying to restart the application", e);
		}
	}
	
}
